package com.agileai.portal.extend.theme;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.agileai.portal.driver.model.Theme;
import com.agileai.util.StringUtil;

public class ThemeHelper {
	public static String getWindowScreenHeight(HttpServletRequest httpRequest){
		HttpSession httpSession = httpRequest.getSession();
		String windowScreenHeight = (String)httpSession.getAttribute(Theme.WindowScreenHeight);
		if (StringUtil.isNullOrEmpty(windowScreenHeight)){
			reloadScreenAttributes(httpRequest, httpSession);
			windowScreenHeight = (String)httpSession.getAttribute(Theme.WindowScreenHeight);
		}
		return windowScreenHeight;
	}
	public static String getWindowScreenWidth(HttpServletRequest httpRequest){
		HttpSession httpSession = httpRequest.getSession();
		String windowScreenWidth = (String)httpSession.getAttribute(Theme.WindowScreenWidth);
		if (StringUtil.isNullOrEmpty(windowScreenWidth)){
			reloadScreenAttributes(httpRequest, httpSession);
			windowScreenWidth = (String)httpSession.getAttribute(Theme.WindowScreenWidth);
		}
		return windowScreenWidth;
	}	
	private static void reloadScreenAttributes(HttpServletRequest httpRequest,HttpSession newSession){
		Cookie[] cookies = httpRequest.getCookies();
		int len = cookies.length;
		for(int i=0; i<len; i++) {
			Cookie cookie = cookies[i];
			String cookieName = cookie.getName();
			if(cookieName.equals(Theme.WindowScreenWidth)) {
				String windowScreenWidth = cookie.getValue();
				newSession.setAttribute(Theme.WindowScreenWidth,windowScreenWidth);
			}
			
			if(cookieName.equals(Theme.WindowScreenHeight)) {
				String windowScreenHeight = cookie.getValue();
				newSession.setAttribute(Theme.WindowScreenHeight,windowScreenHeight);
			}
		}
	}
	
	public static String getReletivePath(Theme theme,String customCssJsURL){
		String result = null;
		if (customCssJsURL.indexOf("${themePath}") > -1){
			String themePageURL = theme.getThemePageURL();
			int lastSplashIndex = themePageURL.lastIndexOf("/");
			String themePath = themePageURL.substring(0,lastSplashIndex); 
			result = customCssJsURL.replaceAll("\\$\\{themePath\\}", themePath);
		}else{
			result = customCssJsURL;
		}
		return result;
	}
}